﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;


/// <summary>
/// Handler 的摘要说明
/// </summary>
public abstract class Handler
{
	public Handler(HttpContext context)
	{
        this.Request = context.Request;
        this.Response = context.Response;
        this.Context = context;
        //this.Server = context.Server;
	}

    public abstract void Process();

    protected void WriteJson(object response)
    {
        string jsonpCallback = Request.Query["callback"],
            json = JsonConvert.SerializeObject(response);
        string result = "";
        if (string.IsNullOrWhiteSpace(jsonpCallback))
        {
            Response.Headers.Add("Content-Type", "text/plain");
            result = json;
        }
        else 
        {
            Response.Headers.Add("Content-Type", "application/javascript");
            result = string.Format("{0}({1});", jsonpCallback, json);
        }

        byte[] bytes = System.Text.Encoding.Default.GetBytes(result);
        Response.Body.WriteAsync(bytes, 0, bytes.Length).Wait();
        //Response.Body.EndWrite(Response.Body.WriteAsync(bytes, 0, bytes.Length));
    }

    public HttpRequest Request { get; private set; }
    public HttpResponse Response { get; private set; }
    public HttpContext Context { get; private set; }
    //public HttpServerUtility Server { get; private set; }
}